package com.lss.controller;

import com.lss.bean.LoginControllerUser;
import com.lss.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class LoginController {

    /**
     * 容器自动注入LoginService
     */
    @Autowired
    LoginService loginService;

    /**
     * 验证登录的账号和密码
     */
    @RequestMapping("/checkLoginIfSuccessful")
    public String checkLoginIfSuccessful(String username, String password, String verificationCode, HttpSession httpSession, Model model) {
        String randomVerificationCode = (String) httpSession.getAttribute("verificationCode");
        if (!verificationCode.equals(randomVerificationCode)) {
            httpSession.setAttribute("msg", "验证码输入错误");
            return "redirect:/login";
        }
        LoginControllerUser loginControllerUser = loginService.checkLoginSuccessful(username, password);

        if (loginControllerUser != null) {
            httpSession.setAttribute("login", loginControllerUser);
            return "redirect:/student";
        }
        httpSession.setAttribute("msg", "用户名或密码错误");
        return "redirect:/login";
    }

    /**
     * 传递验证码
     */
    @ResponseBody
    @RequestMapping("/verificationCode")
    public void verificationCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //服务器通知浏览器不要缓存
        resp.setHeader("pragma", "no-cache");
        resp.setHeader("cache-control", "no-cache");
        resp.setHeader("expires", "0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        req.getSession().setAttribute("verificationCode", checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image, "PNG", resp.getOutputStream());
    }

    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 验证俩次输入的新密码是否一样
     */
    @ResponseBody
    @RequestMapping("/isItTheSame")
    public int isItTheSame(String password, String checkPassword, String oldPassword, HttpSession session) {
        LoginControllerUser login = (LoginControllerUser) session.getAttribute("login");
        String username = login.getUsername();   //获取登录用户名
        String queryPassword = loginService.queryPassword(username);  //查询出密码
        if (!queryPassword.equals(oldPassword)) {
            session.setAttribute("successful", "1");
            return 0;
        }
        if (password.equals(checkPassword)) {
            session.setAttribute("successful", "2");
            return 1;
        } else {
            session.setAttribute("successful", "3");
            return 2;
        }
    }

    /**
     * 修改登录密码
     */
    @RequestMapping("/change")
    public String changePassword(String oldPassword, String checkPassword, String password, HttpSession session, Model model) {
        LoginControllerUser login = (LoginControllerUser) session.getAttribute("login");
        String username = login.getUsername();   //获取登录用户名
        String passwordCheck = login.getPassword();
        if (!oldPassword.equals(passwordCheck)) {    //密码输入错误
            model.addAttribute("msgOld", "密码输入错误");
            return "changePassword";
        } else if (!checkPassword.equals(password)) {   //新密码俩次输入不一致
            model.addAttribute("msg", "俩次密码输入不一致");
            return "changePassword";
        }
        loginService.changePassword(username, password);
        session.removeAttribute("login");   //修改密码，移除session
        return "ChangePasswordAfter";   //跳转到ChangePasswordAfter,然后此页面再跳转到登录页，跳出frameset子页面
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/home")
    public String yes() {
        return "home";
    }

}